using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.ComponentModel;
using System.Data;
using ACME.Northwind.DataTransfer;
using ACME.Northwind.Business.Objects;
using Widgetsphere.Core.DataAccess;
using System.Linq.Expressions;
using ACME.Northwind.Business.LINQ;
using Widgetsphere.Core.Util;
using System.Reflection;

namespace ACME.Northwind.DataTransfer.Extensions
{
	public static partial class CustomerCustomerDemoExtension
	{
		#region Fill DAL

		/// <summary>
		/// Populate a DAL object from its corresponding DTO.
		/// </summary>
		/// <param name="item">The empty DAL object.</param>
		/// <param name="dtoItem">The source DTO to load.</param>
		public static void Fill(this CustomerCustomerDemo item, CustomerCustomerDemoDTO dtoItem)
		{
			if (dtoItem == null) throw new Exception("The CustomerCustomerDemo DTO cannot be null.");
			if (item == null) throw new Exception("The CustomerCustomerDemo item cannot be null.");
			DataRow dr = ((DataRow)((IWrappingClass)item).WrappedClass);
			dr["CustomerID"] = dtoItem.CustomerId;
			dr["CustomerTypeID"] = dtoItem.CustomerTypeId;
		}

		#endregion

		#region Fill DTO

		/// <summary>
		/// Populate a DTO object collection from its corresponding DAL object collection.
		/// </summary>
		/// <param name="list">The destination DTO collection.</param>
		/// <param name="customercustomerdemoCollection">The source DAL collection.</param>
		public static void Fill(this List<CustomerCustomerDemoDTO> list, CustomerCustomerDemoCollection customercustomerdemoCollection)
		{
			if (customercustomerdemoCollection == null) throw new Exception("The CustomerCustomerDemo collection cannot be null.");
			if (list == null) list = new List<CustomerCustomerDemoDTO>();
			foreach (CustomerCustomerDemo item in customercustomerdemoCollection)
			{
				CustomerCustomerDemoDTO newItem = new CustomerCustomerDemoDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Populate a DTO object from its corresponding DAL object.
		/// </summary>
		/// <param name="item">The source DAL object.</param>
		/// <param name="dtoItem">The empty DTO to load.</param>
		public static void Fill(this CustomerCustomerDemoDTO dtoItem, CustomerCustomerDemo item)
		{
			if (dtoItem == null) throw new Exception("The CustomerCustomerDemo DTO cannot be null.");
			if (item == null) throw new Exception("The CustomerCustomerDemo item cannot be null.");
			dtoItem.CustomerTypeId = item.CustomerTypeId;
			dtoItem.CustomerId = item.CustomerId;
			dtoItem.CreatedDate = item.CreatedDate;
			dtoItem.CreatedBy = item.CreatedBy;
			dtoItem.ModifiedDate = item.ModifiedDate;
			dtoItem.ModifiedBy = item.ModifiedBy;
		}

		#endregion

		#region RunSelect

		/// <summary>
		/// Select all objects from store.
		/// </summary>
		public static void RunSelect(this List<CustomerCustomerDemoDTO> list)
		{
			if (list == null) list = new List<CustomerCustomerDemoDTO>();
			CustomerCustomerDemoCollection retval = CustomerCustomerDemoCollection.RunSelect();
			foreach (CustomerCustomerDemo item in retval)
			{
				CustomerCustomerDemoDTO newItem = new CustomerCustomerDemoDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<CustomerCustomerDemoDTO> list, Expression<Func<CustomerCustomerDemoQuery, bool>> where)
		{
			if (list == null) list = new List<CustomerCustomerDemoDTO>();
			list.Fill(CustomerCustomerDemoCollection.RunSelect(where));
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a paged result set.
		/// </summary>
		public static PagedQueryResults<CustomerCustomerDemoDTO> RunSelect(this List<CustomerCustomerDemoDTO> list, string pageSize, string page, string sortOrder, string sortColumn, string linq)
		{
			if (list == null) list = new List<CustomerCustomerDemoDTO>();
			#region Setup Variables and Error Check
			int po;
			int rpp;

			if (!int.TryParse(page, out po)) throw new Exception("The page number number is not a valid integer!");
			if (po < 1) po = 1;

			if (!int.TryParse(pageSize, out rpp)) throw new Exception("The page size is not a valid integer!");
			if (rpp < 1) rpp = 1;

			CustomerCustomerDemo.FieldNameConstants sortField;
			try
			{
				sortField = (CustomerCustomerDemo.FieldNameConstants)Enum.Parse(typeof(CustomerCustomerDemo.FieldNameConstants), sortColumn);
			}
			catch (Exception ex)
			{
				throw new Exception("The sort field is not valid!");
			}

			bool ascending = (sortOrder.ToLower() == "asc" || sortOrder.ToLower() == "ascending");
			#endregion

			PagedQueryResults<CustomerCustomerDemoDTO> retVal = new PagedQueryResults<CustomerCustomerDemoDTO>();
			CustomerCustomerDemoPaging paging = new CustomerCustomerDemoPaging();
			paging.RecordsperPage = rpp;
			paging.PageIndex = po;
			paging.OrderByList.Add(new CustomerCustomerDemoPagingFieldItem(sortField, ascending));

			CustomerCustomerDemoCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = CustomerCustomerDemoCollection.RunSelect(x => true, paging);
			}
			else
			{
				MethodInfo method = LINQDynamicCompile.GetLINQMethodPaged(linq, "ACME.Northwind.Business", "CustomerCustomerDemo");
				dalList = (CustomerCustomerDemoCollection)method.Invoke(null, new object[] { paging });
			}

			if (list == null) list = new List<CustomerCustomerDemoDTO>();
			foreach (CustomerCustomerDemo item in dalList)
			{
				CustomerCustomerDemoDTO newItem = new CustomerCustomerDemoDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}

			retVal.CurrentPage = paging.PageIndex;
			double totalPages = Math.Ceiling((double)paging.RecordCount / (double)paging.RecordsperPage);
			retVal.TotalPages = (int)totalPages;
			retVal.TotalRecords = paging.RecordCount;
			retVal.GridData = list;

			return retVal;
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<CustomerCustomerDemoDTO> list, string linq)
		{
			if (list == null) list = new List<CustomerCustomerDemoDTO>();

			CustomerCustomerDemoCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = CustomerCustomerDemoCollection.RunSelect(x => true);
			}
			else
			{
				MethodInfo method = LINQDynamicCompile.GetLINQMethodAll(linq, "ACME.TestProj.Business", "CustomerCustomerDemo");
				dalList = (CustomerCustomerDemoCollection)method.Invoke(null, new object[] { });
			}

			if (list == null) list = new List<CustomerCustomerDemoDTO>();
			foreach (CustomerCustomerDemo item in dalList)
			{
				CustomerCustomerDemoDTO newItem = new CustomerCustomerDemoDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		#endregion

		#region Persist

		/// <summary>
		/// Persists this object to store.
		/// </summary>
		public static CustomerCustomerDemoDTO Persist(this CustomerCustomerDemoDTO customercustomerdemo)
		{
			if (customercustomerdemo == null) throw new Exception("The CustomerCustomerDemo DTO cannot be null.");
			//Find this object and if not exists, create a new one
			CustomerCustomerDemo newItem = ACME.Northwind.Business.Objects.CustomerCustomerDemo.SelectUsingPK(customercustomerdemo.CustomerId, customercustomerdemo.CustomerTypeId);
			CustomerCustomerDemoCollection customercustomerdemoCollection = null;
			if (newItem == null)
			{
				customercustomerdemoCollection = new CustomerCustomerDemoCollection();
				newItem = customercustomerdemoCollection.NewItem();
			}
			else
			{
				customercustomerdemoCollection = newItem.ParentCollection;
			}	

			//Populate the DAL and perist
			newItem.Fill(customercustomerdemo);
			if (!newItem.IsParented) customercustomerdemoCollection.AddItem(newItem);
			customercustomerdemoCollection.Persist();

			//Re-populate the passed-in object from the DAL
			customercustomerdemo.Fill(newItem);
			return customercustomerdemo;
		}

		/// <summary>
		/// Persists this collection to store.
		/// </summary>
		public static bool Persist(this List<CustomerCustomerDemoDTO> customercustomerdemoList)
		{
			if (customercustomerdemoList == null) throw new Exception("The CustomerCustomerDemo DTO list cannot be null.");
			//Get all objects from the database that match PK
			CustomerCustomerDemoCollection customercustomerdemoCollection = new CustomerCustomerDemoCollection();
			System.Collections.ArrayList keyList = new System.Collections.ArrayList();
			foreach (CustomerCustomerDemoDTO dto in customercustomerdemoList)
			{
				keyList.Add(new CustomerCustomerDemoPrimaryKey(dto.CustomerId, dto.CustomerTypeId));
			}			
			customercustomerdemoCollection.SubDomain.AddSelectCommand(new ACME.Northwind.Business.SelectCommands.CustomerCustomerDemoSelectByPks(keyList));
			customercustomerdemoCollection.SubDomain.RunSelectCommands();

			//Now find and populate the objects for saving
			foreach (CustomerCustomerDemoDTO dto in customercustomerdemoList)
			{
				CustomerCustomerDemo customercustomerdemo = (from x in (IEnumerable<CustomerCustomerDemo>)customercustomerdemoCollection
					where x.CustomerId == dto.CustomerId && x.CustomerTypeId == dto.CustomerTypeId
					select x).FirstOrDefault();

				if (customercustomerdemo == null) customercustomerdemo = customercustomerdemoCollection.NewItem();
				customercustomerdemo.Fill(dto);
				if (!customercustomerdemo.IsParented) customercustomerdemoCollection.AddItem(customercustomerdemo);
			}
			customercustomerdemoCollection.Persist();

			//Re-populate the passed-in object from the DAL
			List<CustomerCustomerDemoDTO> deletedList = new List<CustomerCustomerDemoDTO>();
			foreach (CustomerCustomerDemoDTO dto in customercustomerdemoList)
			{
				CustomerCustomerDemo customercustomerdemo = (from x in (IEnumerable<CustomerCustomerDemo>)customercustomerdemoCollection
					where x.CustomerId == dto.CustomerId && x.CustomerTypeId == dto.CustomerTypeId
					select x).FirstOrDefault();

				if (customercustomerdemo != null) dto.Fill(customercustomerdemo);
				else deletedList.Add(dto);
			}

			//Remove the items that are no longer there (if any)
			foreach (CustomerCustomerDemoDTO dto in deletedList)
			{
				customercustomerdemoList.Remove(dto);
			}

			return true;
		}

		#endregion

		#region CustomerCustomerDemo Select by Column

		#endregion

		#region CustomerCustomerDemo SelectUsingPK

		/// <summary>
		/// Select a single object from this collection by its primary key.
		/// </summary>
		public static void SelectUsingPK(this CustomerCustomerDemoDTO customercustomerdemo, string customerid, string customertypeid)
		{
			CustomerCustomerDemo item = ACME.Northwind.Business.Objects.CustomerCustomerDemo.SelectUsingPK(customerid, customertypeid);
			customercustomerdemo.Fill(item);
		}

		#endregion

		#region CustomerCustomerDemo Select By Foreign Key

		/// <summary>
		/// Populate a 'CustomerDemographic' DTO object collection from its relationship with the 'CustomerCustomerDemo' table.
		/// </summary>
		public static void SelectByCustomerDemographic(this List<CustomerCustomerDemoDTO> CustomerCustomerDemoList, string customertypeid)
		{
			CustomerCustomerDemoCollection list = CustomerCustomerDemoCollection.RunSelect(x => x.CustomerTypeId == customertypeid);
			foreach (CustomerCustomerDemo item in list)
			{
				CustomerCustomerDemoDTO newItem = new CustomerCustomerDemoDTO();
				newItem.Fill(item);
				CustomerCustomerDemoList.Add(newItem);
			}
		}

		/// <summary>
		/// Populate a 'Customer' DTO object collection from its relationship with the 'CustomerCustomerDemo' table.
		/// </summary>
		public static void SelectByCustomer(this List<CustomerCustomerDemoDTO> CustomerCustomerDemoList, string customerid)
		{
			CustomerCustomerDemoCollection list = CustomerCustomerDemoCollection.RunSelect(x => x.CustomerId == customerid);
			foreach (CustomerCustomerDemo item in list)
			{
				CustomerCustomerDemoDTO newItem = new CustomerCustomerDemoDTO();
				newItem.Fill(item);
				CustomerCustomerDemoList.Add(newItem);
			}
		}

		#endregion

	}

}
